exports.searchAgentCommissionRecord = function(req,res){

    //获取参数信息
    var restfulParams = req.routeInfo.restfulParams;

    //最终结果
    var resultData = {};

    //销售人员列表
    var salesData  = [];

    //利润分成数据
    var profitSharingRecordData = [];
    
    //1.查询该代理商是否有自定义提成规则设置
    function searchCustomCommissionRules(cb){

        R.SEND_HTTP(
            req,
            res,
            {
                url: CORE_APIConfig.coreAPI.organizationStructureExtensionInfoSearch.Request_Api_Url + "/os_id/" + restfulParams.os_id,
                method : 'POST',
                data : {
                    fields : "osei_agent_percentage"
                }
            },
            function (data) {

                resultData.commissionRulesData = data.result.data[0].osei_agent_percentage;

                cb();
                
            }
        )
    }

    //2.判断是否需要进行统一规则的获取
    function searchGlobalRules(cb){

        //如果不为0，直接使用自己的规则，否则需要获取统一规则
        if(resultData.commissionRulesData != '0'){
           return cb();  
        }


        R.SEND_HTTP(
            req,
            res,
            {
                url: CORE_APIConfig.coreAPI.artCommissionConfigSearch.Request_Api_Url,
                method : 'GET'
            },
            function (data) {

                resultData.commissionRulesData = data.result.data[0].cc_agent_percentage;

                cb();
                
            }
        )
        
    }

    //查询该代理下的销售人员
    function searchAgentSales(cb){

        R.SEND_HTTP(
            req,
            res,
            {
                url: CORE_APIConfig.coreAPI.userSearch.Request_Api_Url + "/u_master_osid/" + restfulParams.os_id,
                method : 'POST',
                data : {
                    fields : `
                        u_id,
                        u_nickname
                    `
                }
            },
            function (data) {

                var userArr = data.result.data;

                salesData = userArr;

                cb();
                
            }
        )

    }

    //查询每个销售的订单相关信息
    function searchSalesOrder(cb){

        F.SerialEach(salesData,function(item,index,callback){

            //获取该代理下所有销售的订单数据
            R.SEND_HTTP(
                req,
                res,
                {
                    url: config.external_server.apiAddress + "/organization/search_art_product_order/apo_status/1/apo_invite_code/" + item.u_id,
                    method : 'POST',
                    data   : {
                        fields : `apo_real_pay`
                    }
                },
                function (data) {

                    //计算成交总数 和 成交金额
                    var buyCount = data.result.data.length;
                    var buyMoney = 0.0;

                    for(var i=0;i<data.result.data.length;i++){
                        buyMoney += parseFloat(data.result.data[i].apo_real_pay);
                    }

                    item.buyCount = buyCount;
                    item.buyMoney = buyMoney.toFixed(2);
                
                    callback();
                    
                }
            )

        },cb)

    }

    //计算所有销售的总成交数 和 成交金额
    function searchAllSalesOrder(cb){

        var allBuyCount  = 0;
        var allBuyMoney  = 0.0;
        var allCommissionMoney = 0.0;

        for(var i=0;i<salesData.length;i++){

            allBuyCount  += parseInt(salesData[i].buyCount);
            allBuyMoney  += parseFloat(salesData[i].buyMoney);

        }

        //计算提成金额
        allCommissionMoney = allBuyMoney * (resultData.commissionRulesData/100);

        resultData.allBuyCount         = allBuyCount;
        resultData.allBuyMoney         = allBuyMoney;
        resultData.allCommissionMoney  = allCommissionMoney.toFixed(2);

        cb();

    }

    //查询该代理商的结算记录
    function searchSettlementData(cb){

        R.SEND_HTTP(
            req,
            res,
            {
                url: CORE_APIConfig.coreAPI.settlementRecordSearch.Request_Api_Url + "/sr_osid/" + restfulParams.os_id + "/sort_order/sr_id-desc",
                method : 'POST'
            },
            function (data) {

                resultData.settlementData = data.result.data;

                cb();
                
            }
        )
    }

    //查询利润分成记录信息
    function searchProfitSharing(cb){

        R.SEND_HTTP(
            req,
            res,
            {
                url: CORE_APIConfig.coreAPI.profitSharingRecordSearch.Request_Api_Url + "/psr_osid/" + restfulParams.os_id,
                method : 'POST',
                data   : {
                    fields : "psr_id,psr_sales_profit_sharing_money,psr_reward_money"
                }
            },
            function (data) {

                profitSharingRecordData = data.result.data;

                cb();
                
            }
        )

    }

    //计算剩余结算金额
    function calculateResidualSettlement(cb){

        //获取所有利润分成金额
        var totalProfits = 0.0;
        for(var i=0;i<profitSharingRecordData.length;i++){
            totalProfits += (parseFloat(profitSharingRecordData[i].psr_sales_profit_sharing_money) + parseFloat(profitSharingRecordData[i].psr_reward_money));
        }

        //获取已结算金额
        var totalSettlement = 0.0;
        for(var i=0;i<resultData.settlementData.length;i++){
            totalSettlement += parseFloat(resultData.settlementData[i].sr_money);
        }

        //计算剩余结算金额
        var remainingMoney = totalProfits - totalSettlement;

        resultData.totalProfits    = totalProfits;
        resultData.totalSettlement = totalSettlement;
        resultData.remainingMoney  = remainingMoney;
        
        cb();

    }

    F.Serial([searchCustomCommissionRules,searchGlobalRules,searchAgentSales,searchSalesOrder,searchAllSalesOrder,searchSettlementData,searchProfitSharing,calculateResidualSettlement],() => {
        RES.successResponse(res,resultData);
    })

}